<template>
  <div>
    <link rel="stylesheet"
          href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
    <!-- 地图容器 -->
    <div id='container'></div>
  </div>
</template>
<script>
export default {
  props: {
    fkRuralId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      sliced: [],
      ruralList: [],
      // 地图key
      key: 'a3905d3985de06d3cf69aa47435a96f8',
      // 地图默认样式
      defaultStyle: {
        resizeEnable: true, // 是否监控地图容器尺寸变化，默认值为false
        rotateEnable: true, // 地图是否可旋转，3D视图默认为true，2D视图默认false。
        pitchEnable: true, // 是否允许设置俯仰角度，3D视图下为true，2D视图下无效。
        showLabel: false, // 是否显示文字
        zoom: 15, // 地图显示的缩放级别,3D地图下，zoom值，可以设置为浮点数。
        pitch: 60, // 俯仰角度，默认0，[0,83]，2D地图下无效 。
        rotation: 30, // 旋转角度
        viewMode: '3D', // 开启3D视图,默认为关闭
        buildingAnimation: true, // 楼块出现是否带动画
        expandZoomRange: true, // 是否支持可以扩展最大缩放级别,和zooms属性配合使用,设置为true的时候，zooms的最大级别在PC上可以扩大到20级，移动端还是高清19/非高清20
        zooms: [3, 20], // 地图显示的缩放级别范围
        center: [120.716018379, 30.881093815], // 地图中心点坐标值
        skyColor: '#000001', // 调整天空颜色，配合自定义地图，3D视图有效
        mapStyle: 'amap://styles/darkblue' // 设置地图的显示样式
      },
      nMap: null,
      mapAnimateControl: false,
      adCode: 330000, // 370503
      depth: 2,
      layerList: [],
      mask: [],
      // colorList: [
      //   ['rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)', 'rgba(151 154 151, 0.5)'],
      //   ['rgba(111, 164, 26, 0.5)', 'rgba(128, 208, 64, 0.5)', 'rgba(132, 232, 53, 0.5)', 'rgba(111, 222, 23, 0.5)', 'rgba(121, 248, 19, 0.5)', 'rgba(103, 230, 1, 0.5)', 'rgba(111, 164, 26, 0.5)', 'rgba(128, 208, 64, 0.5)', 'rgba(132, 232, 53, 0.5)', 'rgba(111, 222, 23, 0.5)', 'rgba(121, 248, 19, 0.5)', 'rgba(103, 230, 1, 0.5)', 'rgba(111, 164, 26, 0.5)', 'rgba(128, 208, 64, 0.5)', 'rgba(132, 232, 53, 0.5)', 'rgba(111, 222, 23, 0.5)', 'rgba(121, 248, 19, 0.5)', 'rgba(103, 230, 1, 0.5)', 'rgba(111, 164, 26, 0.5)', 'rgba(128, 208, 64, 0.5)', 'rgba(132, 232, 53, 0.5)', 'rgba(111, 222, 23, 0.5)', 'rgba(121, 248, 19, 0.5)', 'rgba(103, 230, 1, 0.5)'],
      //   ['rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)', 'rgba(237, 228, 76, 0.5)'],
      //   ['rgba(230, 61, 58, 0.5)', 'rgba(255, 67, 64, 0.5)', 'rgba(228, 32, 29, 0.5)', 'rgba(250, 27, 23, 0.5)', 'rgba(244, 4, 0, 0.5)', 'rgba(230, 61, 58, 0.5)', 'rgba(255, 67, 64, 0.5)', 'rgba(228, 32, 29, 0.5)', 'rgba(250, 27, 23, 0.5)', 'rgba(244, 4, 0, 0.5)', 'rgba(230, 61, 58, 0.5)', 'rgba(255, 67, 64, 0.5)', 'rgba(228, 32, 29, 0.5)', 'rgba(250, 27, 23, 0.5)', 'rgba(244, 4, 0, 0.5)', 'rgba(230, 61, 58, 0.5)', 'rgba(255, 67, 64, 0.5)', 'rgba(228, 32, 29, 0.5)', 'rgba(250, 27, 23, 0.5)', 'rgba(244, 4, 0, 0.5)', 'rgba(230, 61, 58, 0.5)', 'rgba(255, 67, 64, 0.5)', 'rgba(228, 32, 29, 0.5)', 'rgba(250, 27, 23, 0.5)', 'rgba(244, 4, 0, 0.5)']
      // ]
      // colorList: [
      //   'rgba(151 154 151, 0.8)',
      //   'rgba(111, 164, 26, 0.8)',
      //   'rgba(237, 228, 76, 0.8)',
      //   'rgba(230, 61, 58, 0.8)'
      // ]
      colorList: [
        'rgba(151, 154, 151, 0.8)',
        'rgba(121, 170, 65, 1)',
        'rgba(255, 214, 0, 1)',
        'rgba(237, 66, 48, 1)'
      ]
    }
  },
  components: {
  },
  created () {
    // eslint-disable-next-line no-undef
    // this.nMap = new AMap.Map('container', this.defaultStyle)
    if (this.fkRuralId && this.fkRuralId !== null && this.fkRuralId !== '') {
      // 获取农村网格数据
      this.$Ajax(
        '/ruralIndex/getRuralGridDistributionByFkRuralId?fkRuralId=' + this.fkRuralId,
        'get',
        {},
        (res) => {
          if (res.data) {
            // this.ruralList = res.data.filter(item => item.coordinates && item.gridLevel > 0)
            this.ruralList = res.data.filter(item => item.coordinates)
            if (this.ruralList.length !== 0) {
              const ruraCenter = res.data.map(item => {
                return item.centerCoordinates.split(',')
              }).reduce((list, item) => {
                if (list.length === 0) {
                  list[0] = item[0] * 1
                  list[1] = item[1] * 1
                } else {
                  list[0] += item[0] * 1
                  list[1] += item[1] * 1
                }
                return list
              }, []).map(item => {
                return item / res.data.length
              })
              // 设置地图中心点坐标
              this.defaultStyle.center = ruraCenter
              // this.defaultStyle.mask = this.ruralList.map(item => {
              //   if (JSON.parse(item.coordinates).length !== 1) {
              //     return JSON.parse(item.coordinates).reduce((list, item) => {
              //       item.forEach(items => {
              //         list.push(...items)
              //       })
              //       return list
              //     }, [])
              //   } else {
              //     return JSON.parse(item.coordinates)
              //   }
              // })
              this.ruralList.forEach(item => {
                if (JSON.parse(item.coordinates).length !== 1) {
                  JSON.parse(item.coordinates).forEach(items => {
                    this.mask.push(items)
                  })
                } else {
                  this.mask.push(JSON.parse(item.coordinates))
                }
              })
              // 为 Map 实例指定掩模的路径，各图层将只显示路径范围内图像，3D视图下有效。
              this.defaultStyle.mask = this.mask
            } else {
              this.defaultStyle.mask = []
            }
            this.init()
          }
        }
      )
    }
  },
  methods: {
    init () {
      this.loadScript()
    },
    /**
       * 加载脚本
       */
    loadScript () {
      // 添加 JS API 的入口脚本标签，并将其中「key」替换为您刚刚申请的 key
      // const url = `https://webapi.amap.com/maps?v=1.4.15&key=${this.key}&callback=onLoad&plugin=Map3D`
      // const jsapi = document.createElement('script')
      // jsapi.charset = 'utf-8'
      // jsapi.src = url
      // document.head.appendChild(jsapi)
      // jsapi.onload = () => {
      this.initMap()
      // }
    },
    /**
       * 实例化AMap对象
       */
    initMap () {
      // const center = this.ruralList[0].centerCoordinates.split(',').map(item => { return Number(item) })
      // center[1] = 30.8049982005
      // this.defaultStyle.center = center
      // this.defaultStyle.center[1] = 30.80377982005
      // window.onLoad = () => {
      // eslint-disable-next-line no-undef
      this.nMap = new AMap.Map('container', this.defaultStyle)
      // // 设置光照
      // eslint-disable-next-line no-undef
      this.nMap.AmbientLight = new AMap.Lights.AmbientLight([1, 1, 1], 0.8)
      // eslint-disable-next-line no-undef
      this.nMap.DirectionLight = new AMap.Lights.DirectionLight([0, 0, 1], [1, 1, 1], 0.1)
      this.setObject3DLayer()
    },
    // 设置地图覆盖物 -- 废弃
    setPolygon () {
      this.ruralList.map(item => {
        // eslint-disable-next-line no-undef
        const polygon = new AMap.Polygon({
          strokeWeight: 5, // 轮廓线宽度
          path: JSON.parse(item.coordinates), // 覆盖物轮廓线的节点坐标数组
          strokeColor: '#0091FF', // 线条颜色
          fillOpacity: '0', // 填充颜色
          zIndex: 999
        })
        polygon.setMap(this.nMap)
      })
    },
    // 设置行政区图层 -- 废弃
    setDistrictLayer () {
      // eslint-disable-next-line no-undef
      AMap.plugin('AMap.DistrictLayer', () => { // 异步加载插件
        // eslint-disable-next-line no-undef
        const disProvince = new AMap.DistrictLayer.Province({
          zIndex: 999,
          adcode: [this.adCode], // 行政区adcode
          depth: this.depth, // 设定数据的层级深度，depth为0的时候只显示国家面，depth为1的时候显示省级，当国家为中国时设置depth为2的可以显示市一级
          styles: {
            fill: (properties) => {
              const obj = this.layerList.filter(item => properties.adcode === item.code)
              if (obj.length === 0) return
              return obj.shift().color
            },
            'province-stroke': 'cornflowerblue', // 省级边界
            'city-stroke': 'blue', // 中国地级市边界
            'county-stroke': 'blue' // 中国区县边界
          }
        })
        disProvince.setMap(this.nMap)
      })
    },
    // 设置3D地图图层
    setObject3DLayer () {
      // eslint-disable-next-line no-undef
      var object3Dlayer = new AMap.Object3DLayer()
      this.nMap.add(object3Dlayer)
      // 3D地图高度
      var height = 750
      // 轮廓线条高度数组
      var height2 = [2, 200, 400, 600, 752]
      // 轮廓线条颜色
      var color = '#fff'
      // 遍历网格数组
      this.ruralList.map((item) => {
        if (JSON.parse(item.coordinates).length !== 1) {
          JSON.parse(item.coordinates).forEach(itemss => {
            // eslint-disable-next-line no-undef
            const boundsOne = []
            itemss.map(items => {
              boundsOne.push(...items.map(item2 => {
                // eslint-disable-next-line no-undef
                return new AMap.LngLat(item2[0], item2[1])
              })
              )
            })
            // eslint-disable-next-line no-undef
            var thinline = new AMap.Object3D.MeshLine({
              path: boundsOne,
              color: color,
              width: 6,
              height: height2
            });
            object3Dlayer.add(thinline)
            // eslint-disable-next-line no-undef
            var prism = new AMap.Object3D.Prism({
              path: boundsOne,
              height: height,
              color: this.colorList[item.gridLevel],
            })
            prism.transparent = true
            object3Dlayer.add(prism)
          })
        } else {
          const boundsTow = []
          JSON.parse(item.coordinates).map(items => {
            boundsTow.push(...items.map(item2 => {
              // eslint-disable-next-line no-undef
              return new AMap.LngLat(item2[0], item2[1])
            })
            )
          })
          // for (var i = 0; i < 5; i++) {
          // eslint-disable-next-line no-undef
          var thinline = new AMap.Object3D.MeshLine({
            path: boundsTow,
            color: color,
            width: 6,
            height: height2[4]
          });
          object3Dlayer.add(thinline)
          // }
          // eslint-disable-next-line no-undef
          var prism = new AMap.Object3D.Prism({
            path: boundsTow,
            height: height,
            // color: 'rgba(36, 96, 198, 0.8)'
            color: this.colorList[item.gridLevel],
          })
          prism.transparent = true
          object3Dlayer.add(prism)
          // var box = new AMap.Object3D.MeshAcceptLights()
          // var geometry = box.geometry;
          // box.textures.push('https://a.amap.com/jsapi_demos/static/texture3d/shuilifang.png')
        }
        // 创建点标记markers
        // eslint-disable-next-line no-undef
        const marker = new AMap.Marker({
          content: this.createMarketContent(item), // 自定义点标记内容
          position: item.centerCoordinates.split(','), // 点标记坐标
          extData: { // 设置点标记额外内容
            name: item,
          },
          // eslint-disable-next-line no-undef
          offset: new AMap.Pixel(-20, -90) // 设置点标记偏移量
        });
        // 创建信息窗体
        // eslint-disable-next-line no-undef
        const infoWindow = new AMap.InfoWindow({
          isCustom: true, // 使用自定义窗体
          // eslint-disable-next-line no-undef
          offset: new AMap.Pixel(174, -104) // 设置信息窗体偏移量
        })
        // 鼠标移入点标记上面触发
        marker.on('mouseover', () => {
          // 设置信息窗体内容
          infoWindow.setContent(this.createInfoWindow(item))
          // 设置信息窗体在地图上打开的位置
          infoWindow.open(this.nMap, marker.getPosition())
        })
        // 鼠标移出点标记上面触发
        marker.on('mouseout', () => {
          infoWindow.close() // 关闭信息窗体
        })
        // 地图上添加点标记
        this.nMap.add(marker)
      })
    },
    // 信息窗体自定义内容
    createInfoWindow (data) {
      // 网格等级
      const level = ['', '优秀', '正常', '较差']
      // 网格等级文字样色
      const color = ['', '#3FB018', '#E9C622', '#F04F43']
      // 信息窗体内容
      const content = `<div class="info-window">
        <div class="corner corner-1"></div>
        <div class="corner corner-2"></div>
        <div class="corner corner-3"></div>
        <div class="corner corner-4"></div>
        <div class="title">${data.gridName}</div>
        <div>网格评级：<span style="color: ${color[data.gridLevel]}">${level[data.gridLevel]}</span></div>
        <div>年份：<span>${data.statisticsYear}</span></div>
        <div>户籍人数：<span>${data.registeredPopulationNumber}</span></div>
        <div>党员人数：<span>${data.partyMemberNumber}</span></div>
      </div>`
      return content
    },
    // 点标记自定义内容
    createMarketContent (data) {
      const colors = '#0c2050'
      const content = `<div class="marker-container">
        <div class="marker-label" style="background-color: ${colors}" data-text="${data.gridName}">
          <span class="marker-label-bg"></span>
        </div>
        <div class="marker-line">
        <div class="marker-line-inside"></div></div>
        <div class="marker-circle">
        <div class="marker-circle-inside"></div></div>
      </div>`;
      return content;
    }
  }
}
</script>

<style scoped="scoped" lang="scss">
#container {
  width: 100%;
  height: 100%;
  position: fixed;
  overflow: hidden;
}
/deep/.amap-container {
  background-image: url(../../assets/images/situationMap/组%20150@2x.png) !important;
  background-repeat: no-repeat !important;
  background-size: cover;
  background-position: center 100%;
}
/deep/ .info-window {
  background: rgba(1, 10, 39, 0.5);
  border: 1px solid rgba(1, 10, 39, 1);
  color: #fff;
  font-size: 14px;
  padding: 8px 12px;
  position: relative;
  .title {
    font-weight: 700;
  }
  span {
    font-weight: 700;
  }
  .corner {
    position: absolute;
    width: 10px;
    height: 10px;
    border-style: solid;
    border-color: rgb(4, 185, 231);
  }
  .corner-1 {
    left: -2px;
    top: -2px;
    border-left-width: 2px;
    border-top-width: 2px;
    border-right: none;
    border-bottom: none;
  }

  .corner-2 {
    right: -2px;
    top: -2px;
    border-right-width: 2px;
    border-top-width: 2px;
    border-left: none;
    border-bottom: none;
  }

  .corner-3 {
    left: -2px;
    bottom: -2px;
    border-bottom-width: 2px;
    border-left-width: 2px;
    border-top: none;
    border-right: none;
  }

  .corner-4 {
    right: -2px;
    bottom: -2px;
    border-bottom-width: 2px;
    border-right-width: 2px;
    border-top: none;
    border-left: none;
  }
}
::v-deep {
  // rgba(26, 223, 242, 1)
  $mapColor: #41b7f6;
  $mapColors: #22d900;
  $mapBgColor: #080f3d;
  .marker-container {
    transform-style: preserve-3d;
    transform: translateY(-60%) translateX(-50%);
    pointer-events: auto;
    .marker-label {
      position: relative;
      padding: 8px 22px;
      box-sizing: content-box;
      white-space: nowrap;
      width: auto;
      text-align: center;
      color: #fff;
      border-radius: 5px;
      // 0px 0px 15px 6px rgba(65, 183, 246, 0.9) inset,
      box-shadow: 0px 0px 15px 10px rgba(65, 183, 246, 0.5);
      background-color: $mapBgColor;

      .marker-label-bg {
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        border-radius: 10px;
      }

      &:after {
        position: relative;
        content: attr(data-text);
        font-weight: bold;
      }
    }

    .marker-line {
      margin: auto;
      width: 2px;
      height: 120px;
      transform: translateY(10px);

      .marker-line-inside {
        width: 100%;
        height: 100%;
        background: linear-gradient(to bottom, transparent 0%, #41b7f6 100%)
          repeat-y;
        animation-name: hideLine;
        animation-duration: 3s;
        animation-iteration-count: infinite;
      }
    }

    .marker-circle {
      display: flex;
      margin: auto;
      width: 40px;
      height: 40px;
      border: 2px solid $mapColor;
      border-radius: 50%;
      background-color: $mapBgColor;
      box-shadow: 0 0 10px 5px rgba(255, 255, 255, 0.5);
      transition: all;
      align-items: center;
      justify-content: center;
      animation: hideCircle 2s infinite ease-out;

      .marker-circle-inside {
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background-color: $mapColor;
        border: 1px solid #41b7f6;
      }
    }
  }
}
::v-deep .amap-marker:nth-child(2n) .marker-circle {
  animation-delay: 0.3s;
}

@for $i from 1 through 9 {
  ::v-deep .amap-marker:nth-child(#{$i}) .marker-line .marker-line-inside {
    animation-duration: 1.6s;
    animation-delay: 1.6s * $i;
  }
}
@keyframes hideLine {
  0% {
    height: 0px;
  }

  100% {
    height: 120px;
  }
}

@keyframes hideCircle {
  0% {
    opacity: 0;
    transform: rotateX(50deg) translateZ(14px) scale(0.2);
  }

  100% {
    opacity: 0.6;
    transform: rotateX(50deg) translateZ(14px) scale(1);
  }
}
</style>
